package com.glory.gloryquickui.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;

import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * FileName: FileUtils
 * Author: XJH
 * Date: 2021/6/3 11:28
 * Description:
 * History:
 */
public class FileUtils {


    private static final String[][] MIME_MapTable = new String[][]{{".3gp", "video/3gpp"}, {".apk", "application/vnd.android.package-archive"}, {".asf", "video/x-ms-asf"}, {".avi", "video/x-msvideo"}, {".bin", "application/octet-stream"}, {".bmp", "image/bmp"}, {".c", "text/plain"}, {".class", "application/octet-stream"}, {".conf", "text/plain"}, {".cpp", "text/plain"}, {".doc", "application/msword"}, {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, {".xls", "application/vnd.ms-excel"}, {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, {".exe", "application/octet-stream"}, {".gif", "image/gif"}, {".gtar", "application/x-gtar"}, {".gz", "application/x-gzip"}, {".h", "text/plain"}, {".htm", "text/html"}, {".html", "text/html"}, {".jar", "application/java-archive"}, {".java", "text/plain"}, {".jpeg", "image/jpeg"}, {".jpg", "image/jpeg"}, {".js", "application/x-javascript"}, {".log", "text/plain"}, {".m3u", "audio/x-mpegurl"}, {".m4a", "audio/mp4a-latm"}, {".m4b", "audio/mp4a-latm"}, {".m4p", "audio/mp4a-latm"}, {".m4u", "video/vnd.mpegurl"}, {".m4v", "video/x-m4v"}, {".mov", "video/quicktime"}, {".mp2", "audio/x-mpeg"}, {".mp3", "audio/x-mpeg"}, {".mp4", "video/mp4"}, {".mpc", "application/vnd.mpohun.certificate"}, {".mpe", "video/mpeg"}, {".mpeg", "video/mpeg"}, {".mpg", "video/mpeg"}, {".mpg4", "video/mp4"}, {".mpga", "audio/mpeg"}, {".msg", "application/vnd.ms-outlook"}, {".ogg", "audio/ogg"}, {".pdf", "application/pdf"}, {".png", "image/png"}, {".pps", "application/vnd.ms-powerpoint"}, {".ppt", "application/vnd.ms-powerpoint"}, {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, {".prop", "text/plain"}, {".rc", "text/plain"}, {".rmvb", "audio/x-pn-realaudio"}, {".rtf", "application/rtf"}, {".sh", "text/plain"}, {".tar", "application/x-tar"}, {".tgz", "application/x-compressed"}, {".txt", "text/plain"}, {".wav", "audio/x-wav"}, {".wma", "audio/x-ms-wma"}, {".wmv", "audio/x-ms-wmv"}, {".wps", "application/vnd.ms-works"}, {".xml", "text/plain"}, {".z", "application/x-compress"}, {".zip", "application/x-zip-compressed"}, {"", "*/*"}};

    public FileUtils() {
    }

    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals("mounted");
    }

    public static void createFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }

    }

    public static String Bitmap2StrByBase64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, 0);
    }

    public static boolean saveBitmap2SD(Bitmap bmp, String filePath) {
        File file = new File(filePath);

        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            add2Album(file);
            return true;
        } catch (FileNotFoundException var4) {
            var4.printStackTrace();
            return false;
        } catch (IOException var5) {
            var5.printStackTrace();
            return false;
        }
    }

    public static void add2Album(File file) {
        try {
            int angle = readPictureDegree(file.getPath());
            if (angle != 0) {
                amendRotatePhoto(angle, file);
            } else {
                MediaStore.Images.Media.insertImage(InitUtils.Companion.getApp().getContentResolver(), file.getAbsolutePath(), file.getName(), (String) null);
            }
        } catch (FileNotFoundException var2) {
            var2.printStackTrace();
        }

    }

    public static void amendRotatePhoto(int angle, File file) {
        Bitmap bmp = getCompressPhoto(file.getPath());
        Bitmap bitmap = rotaingImageView(angle, bmp);
        String newPath = file.getParent() + "/amend_" + System.currentTimeMillis() + ".jpg";
        saveBitmap2SD(bitmap, newPath);
    }

    public static Bitmap getCompressPhoto(String path) throws OutOfMemoryError {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inSampleSize = 6;
        Bitmap bmp = BitmapFactory.decodeFile(path, options);
        options = null;
        return bmp;
    }

    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        Bitmap returnBm = null;
        Matrix matrix = new Matrix();
        matrix.postRotate((float) angle);

        try {
            returnBm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        } catch (OutOfMemoryError var5) {
            var5.printStackTrace();
        }

        if (returnBm == null) {
            returnBm = bitmap;
        }

        if (bitmap != returnBm) {
            bitmap.recycle();
        }

        return returnBm;
    }

    public static int readPictureDegree(String path) {
        short degree = 0;

        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt("Orientation", 1);
            switch (orientation) {
                case 3:
                    degree = 180;
                    break;
                case 6:
                    degree = 90;
                    break;
                case 8:
                    degree = 270;
            }
        } catch (IOException var4) {
            var4.printStackTrace();
        }

        return degree;
    }

    public static void sendAlbumAddPic(Uri imageUri) {
        Intent intent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
        intent.setData(imageUri);
        InitUtils.Companion.getApp().sendBroadcast(intent);
    }

    public static void openFile(Context context, File file) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        intent.setAction("android.intent.action.VIEW");
        String type = getMIMEType(file);
        if (Build.VERSION.SDK_INT >= 24) {
            if (Build.VERSION.SDK_INT >= 26) {
                boolean hasInstallPermission = context.getPackageManager().canRequestPackageInstalls();
                if (!hasInstallPermission) {
                    ActivityCompat.requestPermissions((Activity) context, new String[]{"android.permission.REQUEST_INSTALL_PACKAGES"}, 6666);
                }
            }

            Uri fileUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(fileUri, type);
        } else {
            intent.setDataAndType(Uri.fromFile(file), type);
        }

        context.startActivity(intent);
    }

    public static String getMIMEType(File file) {
        String type = "*/*";
        String fName = file.getName();
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        } else {
            String end = fName.substring(dotIndex, fName.length()).toLowerCase();
            if (end == "") {
                return type;
            } else {
                for (int i = 0; i < MIME_MapTable.length; ++i) {
                    if (end.equals(MIME_MapTable[i][0])) {
                        type = MIME_MapTable[i][1];
                    }
                }

                return type;
            }
        }
    }

    public static boolean deleteFile(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return false;
        } else {
            File file = new File(filePath);
            return file.exists() ? file.delete() : false;
        }
    }

    public static boolean isFile(String filePath) {
        return !TextUtils.isEmpty(filePath) && (new File(filePath)).isFile();
    }

    public static boolean isSdcardExist() {
        return Environment.getExternalStorageState().equals("mounted");
    }

    public static File createNewFile(String path) {
        File file = new File(path);
        File directory = file.getParentFile();
        if (!directory.exists()) {
            directory.mkdirs();
        }

        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException var4) {
                return null;
            }
        }

        return file;
    }

    public static File setCreatPath(File fileP, String name) {
        File photoTempDir = new File(fileP, name);
        if (!photoTempDir.exists()) {
            photoTempDir.mkdir();
        }

        return photoTempDir;
    }

    public static File setCreatPath(String name, String BASE_PATH) {
        File photoTempDir = new File(getAppBaseDir(BASE_PATH), name);
        if (!photoTempDir.exists()) {
            photoTempDir.mkdir();
        }

        return photoTempDir;
    }

    public static File getAppBaseDir(String BASE_PATH) {
        File sdCard = Environment.getExternalStorageDirectory();
        if (sdCard.exists()) {
            File appBaseDir = new File(sdCard, BASE_PATH);
            if (!appBaseDir.exists()) {
                appBaseDir.mkdir();
            }

            return appBaseDir;
        } else {
            return null;
        }
    }


}
